<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>右键菜单</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        #box {
            width: 400px;
            height: 400px;
            border: 1px solid red;
            position: relative;
            left: 100px;
            top:100px;
        }

        .menu {
            width: 100px;
            height: 150px;
            background: lightgreen;
            display: none;
            position: absolute;
        }

        .menu li {
            text-align: center;
            line-height: 30px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="box">
        <div class="menu">
            <ul>
                <li class="add">添加</li>
                <li>查询</li>
                <li>修改</li>
                <li>删除</li>
            </ul>
        </div>
    </div>
    <script>
        let box = document.querySelector("#box")
        let menu = document.querySelector(".menu")
        let add = document.querySelector(".add")
        //给box注册鼠标右键事件
        box.oncontextmenu = function (e) {
            e.preventDefault();  //取消鼠标右键的默认行为
            //判断菜单容器的范围不能超出box
            if (box.offsetWidth + box.offsetLeft > e.pageX &&
                box.offsetHeight + box.offsetTop > e.pageY) {
                //计算出菜单的left
                let left = e.pageX - box.offsetLeft
                //计算出菜单的top
                let top = e.pageY - box.offsetTop

                //先显示menu，才能获取到menu的offsetWidth
                menu.style.display = "block"

                //算出left的最大值
                let maxLeft = box.offsetWidth - menu.offsetWidth - 2
                //算出top的最大值
                let maxTop = box.offsetHeight - menu.offsetHeight - 2
                if(left>maxLeft) left = maxLeft
                if(top>maxTop) top = maxTop
                
                menu.style.left = left + 'px'
                menu.style.top = top + 'px'
            }
        }
        //window点击事件
        window.onclick = function (e) {
            if (!menu.contains(e.target)) {
                menu.style.display = "none"
            }
        }
        //添加选项点击事件
        add.onclick = function (e) {
            alert("执行添加")
            menu.style.display = "none"
        }
    </script>
</body>

</html>